//
//  NSNumber-currency.m
//  iContractor
//
//  Created by Jeff LaMarche on 1/15/09.
//  Copyright 2009 Jeff LaMarche Consulting. All rights reserved.
//

#import "NSNumber-currency.h"
#import "NSString-NumberStuff.h"

@implementation NSNumber(currency)
+ (id)numberWithCurrencyString:(NSString *)currencyString
{
	if (![currencyString holdsFloatingPointValue])
		return nil;
	
	NSString *currencySymbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
	NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
	
	NSString *compare = [currencyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	compare = [compare stringByReplacingOccurrencesOfString:groupingSeparator withString:@""];
	compare = [compare stringByReplacingOccurrencesOfString:currencySymbol withString:@""];
	
	return [NSNumber numberWithDouble:[compare doubleValue]];
}
- (NSString *)currencyString
{
	NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
	[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
	
	NSString *ret = [numberFormatter stringFromNumber:self];
	[numberFormatter release];
	return ret;
}
- (BOOL)isEqualToString:(NSString *)compare
{	
	return [compare doubleValue] == [self doubleValue];
}
- (NSComparisonResult)currencyCompare:(NSString *)compare
{
	return [self compare:[NSNumber numberWithDouble:[compare doubleValue]]];
}
- (NSComparisonResult)reverseNumericCompare:(NSNumber *)compare
{
	return [self compare:compare] * -1;
}
@end

@implementation NSString (currency)
- (NSString *)currencyString
{
	return [[NSNumber numberWithFloat:[self doubleValue]] currencyString];
}
@end

@implementation NSNull (currency)
- (float)floatValue
{
	return 0.0;
}
- (NSString *)currencyString
{
	return [[NSNumber numberWithFloat:0.0] currencyString];
}
- (double)doubleValue
{
	return 0.0;
}
@end
